<template>
  <div v-if="props.mode === 'detail'">
    <span>{{ showLabel }}</span>
  </div>
  <el-cascader
    v-else
    v-model="modelValue"
    v-bind="defaultAttr"
    :options="optionsList"
    style="width: 100%"
    @change="handleChange"
  >
  </el-cascader>
</template>

<script setup>
// v-model值
const modelValue = defineModel()

// 输入框配置项
const props = defineProps({
  config: {
    type: Object,
    default: () => {},
  },
  mode: {
    // 'edit' | 'detail' | 'add'
    type: String,
    default: 'detail',
  },
  form: {
    type: Object,
    default: () => {},
  },
})

const defaultAttr = computed(() => {
  // 设置默认绑定值
  let { attrs = {} } = props.config
  // 获取默认项
  attrs['placeholder'] = attrs?.placeholder || `请选择${props.config.label}`
  // 判断禁用
  attrs['disabled'] = props.config?.disabled || false
  return { ...attrs }
})

// 获取value对应label
const showLabel = computed(() => {
  const index = (optionsList.value || []).findIndex((i) => i.value == modelValue.value)
  if (index >= 0) {
    return optionsList.value[index].label
  } else {
    return ''
  }
})

// options项
const optionsList = ref([])
// 解析
const parseOptions = (value) => {
  const { config } = props
  // 返回数组
  if (Array.isArray(config.options)) {
    initOptions(config.options)
    // 返回方法
  } else if (typeof config.options === 'function') {
    const result = config.options(value)
    if (result.then) {
      result
        .then((list) => {
          initOptions(list)
        })
        .catch((err) => {
          initOptions([])
        })
    } else if (Array.isArray(result)) {
      initOptions(result)
    }
  }
}
// 赋值
const initOptions = (options) => {
  optionsList.value = options
}

onMounted(() => {
  parseOptions(props.form)
})
// 监听options
watch(
  () => ({ ...props.form }),
  (newVal, oldVal) => {
    if (props.config.linkage) {
      const linkage = props.config.linkage
      if (typeof linkage === 'string' && newVal[linkage] && newVal[linkage] !== oldVal[linkage]) {
        parseOptions({ ...props.form })
      } else if (Array.isArray(linkage) && linkage.some((i) => newVal[i] && newVal[i] !== oldVal[i])) {
        parseOptions({ ...props.form })
      }
    }
  },
  { deep: true }
)

// 事件
const emits = defineEmits(['change'])
const handleChange = (value) => {
  if (props.config.event) {
    emits('change', value)
  }
}
</script>

<style lang="scss" scoped></style>
